package cn.sciento.transfer.app.service.impl;

import cn.sciento.core.domain.Page;
import cn.sciento.core.exception.CommonException;import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.validation.Validator;
import org.apache.commons.collections4.CollectionUtils;
import cn.sciento.core.util.ValidUtils;
import cn.sciento.transfer.app.service.ConsTenantConfigService;
import cn.sciento.transfer.domain.entity.ConsTenantConfig;
import cn.sciento.transfer.domain.repository.ConsDbConfigRepository;
import cn.sciento.transfer.domain.repository.ConsTenantConfigRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ConsTenantConfigServiceImpl implements ConsTenantConfigService {
  @Autowired
  private ConsDbConfigRepository consDbConfigRepository;
  
  @Autowired
  private ConsTenantConfigRepository consTenantConfigRepository;
  
  @Autowired
  private Validator validator;
  
  public List<ConsTenantConfig> batchInsertConsTenantConfig(List<ConsTenantConfig> consTenantConfigList) {
    if (CollectionUtils.isEmpty(consTenantConfigList))
      return consTenantConfigList; 
    ValidUtils.valid(this.validator, consTenantConfigList);
    Map<Long, List<ConsTenantConfig>> groupByTenantIdMap = consTenantConfigList.stream().collect(Collectors.groupingBy(consTenantConfig -> consTenantConfig.getTenantId()));
    for (List<ConsTenantConfig> list : groupByTenantIdMap.values()) {
      if (list != null && list.size() > 1)
        throw new CommonException("error.tenant.repeat");
    } 
    this.consTenantConfigRepository.batchInsertSelective(consTenantConfigList);
    return consTenantConfigList;
  }
  
  public Page<ConsTenantConfig> pageAndSortConsTenantConfig(PageRequest pageRequest, ConsTenantConfig consTenantConfig) {
    return this.consTenantConfigRepository.pageAndSortConsTenantConfig(pageRequest, consTenantConfig);
  }
  
  public void deleteConsTenantConfig(Long consDbConfigId) {
    ConsTenantConfig querry = new ConsTenantConfig();
    querry.setConsDbConfigId(consDbConfigId);
    List<ConsTenantConfig> select = this.consTenantConfigRepository.select(querry);
    if (CollectionUtils.isNotEmpty(select))
      select.stream().forEach(item -> this.consTenantConfigRepository.deleteByPrimaryKey(item.getConsTenantConfigId())); 
  }
}
